#!/usr/bin/env node

const esbuild = require("esbuild");
const path = require("path");
const fs = require("fs");

// 路径别名插件
const aliasPlugin = {
  name: "alias",
  setup(build) {
    const resolveAlias = (prefix, replacement) => {
      const filter = new RegExp(`^${prefix.replace(/\//g, "\\/")}`);
      build.onResolve({ filter }, (args) => {
        const relativePath = args.path.slice(prefix.length);
        let resolved = path.join(__dirname, "..", replacement, relativePath);

        // 如果解析后的路径是目录，尝试添加 /index
        if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {
          const indexPath = path.join(resolved, "index.ts");
          if (fs.existsSync(indexPath)) {
            resolved = indexPath;
          }
        } else if (!fs.existsSync(resolved)) {
          // 尝试添加 .ts 扩展名
          const withExt = resolved + ".ts";
          if (fs.existsSync(withExt)) {
            resolved = withExt;
          }
        }

        return { path: resolved };
      });
    };

    resolveAlias("@/", "src/");
    resolveAlias("@core/", "src/core/");
    resolveAlias("@modules/", "src/modules/");
  },
};

// 构建配置
const buildESM = async () => {
  await esbuild.build({
    entryPoints: [
      "src/index.ts",
      "src/core/index.ts",
      "src/core/loader.ts",
      "src/modules/calculator/index.ts",
      "src/modules/calculator/calculator.ts",
      "src/modules/calculator/types.ts",
    ],
    bundle: false,
    format: "esm",
    outdir: "dist/esm",
    outbase: "src",
    sourcemap: true,
    plugins: [aliasPlugin],
  });

  // 创建 package.json
  fs.writeFileSync("dist/esm/package.json", '{"type":"module"}');
  console.log("✓ ESM build complete");
};

const buildCJS = async () => {
  await esbuild.build({
    entryPoints: [
      "src/index.ts",
      "src/core/index.ts",
      "src/core/loader.ts",
      "src/modules/calculator/index.ts",
      "src/modules/calculator/calculator.ts",
      "src/modules/calculator/types.ts",
    ],
    bundle: false,
    format: "cjs",
    outdir: "dist/cjs",
    outbase: "src",
    sourcemap: true,
    plugins: [aliasPlugin],
  });

  // 创建 package.json
  fs.writeFileSync("dist/cjs/package.json", '{"type":"commonjs"}');
  console.log("✓ CJS build complete");
};

const buildBrowser = async () => {
  // 非压缩版本
  await esbuild.build({
    entryPoints: ["src/index.ts"],
    bundle: true,
    format: "iife",
    globalName: "Wasmer",
    outfile: "dist/browser/wasmer.js",
    sourcemap: true,
    plugins: [aliasPlugin],
  });

  // 压缩版本
  await esbuild.build({
    entryPoints: ["src/index.ts"],
    bundle: true,
    format: "iife",
    globalName: "Wasmer",
    minify: true,
    outfile: "dist/browser/wasmer.min.js",
    sourcemap: true,
    plugins: [aliasPlugin],
  });

  console.log("✓ Browser build complete");
};

// 主函数
const build = async (target) => {
  try {
    if (target === "esm" || !target) {
      await buildESM();
    }
    if (target === "cjs" || !target) {
      await buildCJS();
    }
    if (target === "browser" || !target) {
      await buildBrowser();
    }
  } catch (error) {
    console.error("Build failed:", error);
    process.exit(1);
  }
};

// 执行构建
const target = process.argv[2];
build(target);
